layui.use(['table','element','upload'], function() {
var table = layui.table,
    $ = layui.jquery,
    layer = layui.layer,
    form = layui.form,
    laytpl = layui.laytpl,
    message = parent.message;
	upload = layui.upload;
	element = layui.element;
var tableIns = table.render({
    elem: '#demo',
    height: 'full-132', //容器高度
    url: '../business/file/list?_'+$.now(),
    where: {sidx: '', order: 'desc'},
    page: true,
    id: 'demo',
    limit: 20,
    cols: [
        [{
            checkbox: true,
            fixed: true
        }, {
            field: 'filename',
            title: '文件名',
            width: 200,
            sort: true
        },
         {
            field: 'url',
            title: '文件路径',
            width: 250
        },
         {
            field: 'createTime',
            title: '创建时间',
            width: 350
        },{
            fixed: 'right',
            title: '操作',
            width: 300,
            align: 'center',
            toolbar: '#barDemo'
        }]
    ],
    done: function(res, curr, count) {
    	
    },
    loading: true,
});
//监听工具条
table.on('tool(demo)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
    var data = obj.data; //获得当前行数据
    var layEvent = obj.event; //获得 lay-event 对应的值
    var tr = obj.tr; //获得当前行 tr 的DOM对象

    if (layEvent === 'del') { //删除
        layer.confirm('确定删除该数据', function(index) {
            layer.close(index);
            //向服务端发送删除指令
            var ids = Array();
            ids.push(data.id);
            $.ajax({
        		type: "POST",
        	    url: "../business/file/delete",
        	    data: JSON.stringify(ids),
        	    dataType: 'JSON',
        	    contentType: 'application/json',
        	    success: function(res){
        	    	if (res.code==0) {
        	        	message.show({
        	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
        	                msg:'操作成功'//提示信息
        	            });
        	        	obj.del(); //删除对应行（tr）的DOM结构
        	        	//tableIns.reload({where: {sidx: '', order: 'desc'}});
        	        } else {
        	        	layer.msg(res.msg, {icon: 2});
        	        }
        		}
        	});
        });
    } else if (layEvent === 'edit') { //编辑
    	$.get("../business/file/info/"+data.id, function(res){
			if(res.code==0){
				var d = {
						businessfile:{
							id:data.id,
							filename: data.filename,
							url:data.url
						}
		        };
				var fileFlg = false;
		        laytpl($('#edit-tpl').html()).render(d, function(html) {
		        	var n=0,timer;
		            layer.open({
		                type: 1,
		                title: '修改',
		                content: html,
		                skin: 'layui-layer-rim', //加上边框
		                area: ['600px', '300px'],
		                btn: ['提交', '取消'],
		                yes: function(index, layero) {
		                    editIndex = index;
		                    $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
		                    if(fileFlg){
		                    	//uploadInst.config.data={id:$("#id").val(),filename:$("#filename").val()};
		                    	$("#myprogress").show();
		                    	$('#formEdit').click();
		                    	   timer = setInterval(function(){
	                  	    	        n = n + Math.random()*10|0;  
	                  	    	        if(n>80){
	                  	    	          n = 80;
	                  	    	          clearInterval(timer);
	                  	    	         // othis.removeClass(DISABLED);
	                  	    	        }
	                  	    	        element.progress('demo', n+'%');
	                  	    	      }, 300+Math.random()*1000);
		                    }
		                    else{
		                    	var businessfile = new Object(); 
		                    	businessfile.id=$("#id").val();
		                    	businessfile.filename=$("#filename").val();
		                    	//var json = JSON.stringify(businessfile); 
	                    		saveOrUpdate(businessfile);
	                    		editIndex && layer.close(editIndex);
		                    	
		                    }
		                },
		                btn2: function(index, layero) {
		                	layer.close(index); //关闭弹出层
		                    $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
		                    return false;
		                },
		                success: function() {
		                    form.render(null, 'form-edit');
		                }
		            });
		            var uploadInst = upload.render({
                        elem: '#menuLogoButton',
                        url: '/comm-cg/business/file/update2',
                        accept: 'file',
                        auto: false, //选择文件后不自动上传
                        bindAction: '#formEdit', //指向一个按钮触发上传
                        choose: function(obj){
                    	    //将每次选择的文件追加到文件队列
                    	    var files = obj.pushFile();
                    	    //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                    	    obj.preview(function(index, file, result){
                    	      //这里还可以做一些 append 文件列表 DOM 的操作
                    	    	$('#url').attr('value', "http://47.94.220.217/comm-cg/basefile/"+file.name); 
                    	      fileFlg=true;
                    	      //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
                    	      //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
                    	    });
                    	  }
                        ,done: function(res){
                          //如果上传失败
                          if(res.code != 0){
                        	  layer.msg(res.msg, {icon: 2});
                          }else{
//                        	  message.show({
//              	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
//              	                msg:'操作成功'//提示信息
//              	            });
                        	  element.progress('demo', '100%');
	                        	clearInterval(timer);
	              	        	tableIns.reload({where: {order: 'desc'}});
	              	        	//上传
	              	        	var businessfile = new Object(); 
	              	        	businessfile.id=$("#id").val();
		                    	businessfile.filename=$("#filename").val();
		                    	businessfile.url=res.msg;
		                    	//var json = JSON.stringify(appversion); 
	                    		saveOrUpdate(businessfile);
	              	        	
	              	        	editIndex && layer.close(editIndex);
              	        	tableIns.reload({where: {order: 'desc'}});
                          }
                          //上传成功
                        }
                        ,error: function(){
                          
                        }
                      });
		    });
			}else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		});
    }
});

$('.kit-search-btns').children('a').off('click').on('click', function() {
    var $that = $(this),
    action = $that.data('action');
    switch (action) {
        case 'add'://新增
        	
			var d = {
					businessfile:{
						id:'',
						filename: '',
						url:''
					}
            };
            //渲染
            laytpl($('#edit-tpl').html()).render(d,
            		
                function(html) {
            	var fileFlg=false;
            	var n=0,timer;
                    layer.open({
                        type: 1,
                        title: '新增',
                        content: html,
                        skin: 'layui-layer-rim', //加上边框
                        area: ['600px', '300px'],
                        btn: ['提交', '取消'],
                        yes: function(index, layero) {
                            editIndex = index;
                            $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
                            if(fileFlg){
		                    	//uploadInst.config.data={filename:$("#filename").val()};
                            	$("#myprogress").show();
		                    	$('#formEdit').click();
		                    	timer = setInterval(function(){
                  	    	        n = n + Math.random()*10|0;  
                  	    	        if(n>80){
                  	    	          n = 80;
                  	    	          clearInterval(timer);
                  	    	         // othis.removeClass(DISABLED);
                  	    	        }
                  	    	        element.progress('demo', n+'%');
                  	    	      }, 300+Math.random()*1000);
		                    }
		                    else{
		                    	var businessfile = new Object(); 
		                    	businessfile.filename=$("#filename").val();
		                    //	var json = JSON.stringify(businessfile); 
	                    		saveOrUpdate(businessfile);
	                    		editIndex && layer.close(editIndex);
		                    }
                        },
                        btn2: function(index, layero) {
                        	layer.close(index); //关闭弹出层
                            $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
                            return false;
                        },
                        success: function() {
                            form.render(null, 'form-edit');
                        }
                    });
                    var uploadInst = upload.render({
                        elem: '#menuLogoButton',
                        url: '/comm-cg/business/file/update2',
                        accept: 'file',
                        auto: false, //选择文件后不自动上传
                        bindAction: '#formEdit', //指向一个按钮触发上传
                        choose: function(obj){
                    	    //将每次选择的文件追加到文件队列
                    	    var files = obj.pushFile();
                    	    //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                    	    obj.preview(function(index, file, result){
                    	      //这里还可以做一些 append 文件列表 DOM 的操作
                    	    	$('#url').attr('value', "http://47.94.220.217/comm-cg/apkfile/"+file.name); 
                    	      fileFlg=true;
                    	      //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
                    	      //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
                    	    });
                    	  }
                        ,done: function(res){
                          //如果上传失败
                          if(res.code != 0){
                        	  layer.msg(res.msg, {icon: 2});
                          }else{
//                        	  message.show({
//              	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
//              	                msg:'操作成功'//提示信息
//              	            });
                        	  element.progress('demo', '100%');
	                        	clearInterval(timer);
	              	        	tableIns.reload({where: {order: 'desc'}});
	              	        	//上传
	              	        	var businessfile = new Object(); 
		                    	businessfile.filename=$("#filename").val();
		                    	businessfile.url=res.msg;
		                    	//var json = JSON.stringify(appversion); 
	                    		saveOrUpdate(businessfile);
	              	        	
	              	        	editIndex && layer.close(editIndex);
              	        	tableIns.reload({where: {order: 'desc'}});
                          }
                          //上传成功
                        }
                        ,error: function(){
                          
                        }
                      });
        	});
            break;
        case 'del-bulk'://批量删除
            var d = table.checkStatus('demo');
            if (d.data.length === 0) {
                layer.msg('请选择要删除的数据');
                return;
            }
            var data = d.data,
                ids = [];
            layui.each(data, function(index, item) {
                ids.push(item.id);
            });
            layer.confirm('确定删除选中的数据', function(index) {
            	layer.close(index);
                //向服务端发送删除指令
                $.ajax({
            		type: "POST",
            	    url: "../business/file/delete",
            	    data: JSON.stringify(ids),
            	    dataType: 'JSON',
            	    contentType: 'application/json',
            	    success: function(res){
            	    	if (res.code==0) {
            	        	message.show({
            	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
            	                msg:'操作成功'//提示信息
            	            });
            	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
            	        } else {
            	        	layer.msg(res.msg, {icon: 2});
            	        }
            		}
            	});
            });
            break;
        }
    });

var saveOrUpdate = function (datas) {
	var url = datas.id == null ? "../business/file/save" : "../business/file/update";
	$.ajax({
		type: "POST",
	    url: url,
	    data: JSON.stringify(datas),
	    dataType: 'JSON',
	    contentType: 'application/json',
	    success: function(res){
	    	if (res.code==0) {
	        	message.show({
	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
	                msg:'操作成功'//提示信息
	            });
	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
	        } else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		}
	});
}

form.render(null, 'kit-search-form');//初始化搜索表单
//监听搜索表单提交
form.on('submit(search)', function(data) {
	//带条件查询
    tableIns.reload({
    	where: {
    		sidx: '', order: 'desc',
    		filename: data.field.filename
    	}
    });
    return false;
});

//var editIndex;
//form.on('submit(formEdit)', function(data) {//监听表单提交
//	var roleIds = Array();
//	$("input:checkbox[name='roleIdList']:checked").map(function (index, elem) {
//		roleIds.push($(elem).val());
//		});
//	data.field.roleIdList = roleIds;
//	saveOrUpdate(data.field);
//	editIndex && layer.close(editIndex); //关闭弹出层
//    return false;
//});

});
